package com.gaozhaoyang.dbutils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.gaozhaoyang.entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

import java.sql.SQLException;
import java.util.List;

/*
 *   dbutils:查询
 *        结果集自动映射:它会自动将查询数据库的结果封装成我们预期的类型
 *           BeanHandler:将一条数据封装到一个java对象
 *           BeanListHandler:将每一条数据封装一个Java对象再将多个java对象放入集合
 *           ScalarHandler:再使用聚合函数返回单个值使用
 *
 * */
public class Dbutils_Demo03 {
    ComboPooledDataSource dataSource =new ComboPooledDataSource();
    QueryRunner qr =new QueryRunner(dataSource);
    @Test
    public void findUser() throws SQLException {
        String sql = "select * from user where username =? and password =?";
        //qr.query(sql,结果集,参数...)
        User user = qr.query(sql, new BeanHandler<User>(User.class), "sunwukong", "123");
        System.out.println(user);
    }
    @Test
    public void findAll() throws SQLException {
        String sql = "select * from user";
        List<User> userList = qr.query(sql, new BeanListHandler<User>(User.class));
        for (User user : userList) {
            System.out.println(user);
        }
    }
    @Test
    public void findCount() throws SQLException {
        String sql = "select count(*) from user";
        Object query = qr.query(sql, new ScalarHandler());
        System.out.println(query);
    }
}
